//
//  UIECGView.m
//  vhStressTest1
//
//  Created by jia yu on 2021/9/8.
//

#import "UIECGReView.h"
#import "UIECGReview3x4Controler.h"
#import "UIECGReview6x2Controler.h"
#import "UIECGReviewLocationView.h"

UIECGReView *staticECGReview;

@interface UIECGReView(){
    CAShapeLayer *ecgShapeLayer;
    UIImageView *leadImageView;
    UIECGReview3x4Controler *control3x4;
    UIECGReview6x2Controler *control6x2;
    float shortLeadPrecent;  //短导联显示的ECG开始位置，在长导联中的百分比， from 0.f to 1.f
}
@end

@implementation UIECGReView
@synthesize style;
@synthesize locationView;
@synthesize ecgsArray;
@synthesize endECGSeconds;
@synthesize longLeadChangedHandler;
@synthesize longLead;
@synthesize pix_per_mm,ECG_rate,y_rate,x_speed;
@synthesize isContinunceMode;
@synthesize dataSource;
@synthesize bgView;
@synthesize leadNameFontDictionary;
@synthesize lineWidth,lineColor;

+(UIECGReView *)shared{
    return staticECGReview;
}

-(void)closeView{
    self.alpha = 0.f;
    return;
}

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        staticECGReview = self;
        UIECGReView * __strong strongSelf = self;
        self.layer.masksToBounds = YES;
        self.backgroundColor = [UIColor clearColor];
        isContinunceMode = NO;
        lineWidth = 1.2f;
        lineColor = [vhECGTools colorFromHEXString:@"1d2023"];
        
        NSMutableParagraphStyle *p1 = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        p1.alignment = NSTextAlignmentCenter;
        p1.lineBreakMode = NSLineBreakByClipping;
        leadNameFontDictionary = @{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Medium" size:8.f],
                                     NSForegroundColorAttributeName:[UIColor blackColor],
                                      NSBackgroundColorAttributeName:[UIColor clearColor],
                                     NSParagraphStyleAttributeName:p1};
        
        bgView = [[UIECGBackgroundView alloc] initWithFrame:CGRectMake(0.f, 0.f, frame.size.width, frame.size.height)];
        bgView.background_color = [UIColor whiteColor];
        bgView.bg10mmColor = [vhECGTools colorFromHEXString:@"94cfd1"];
        bgView.bg5mmColor = [vhECGTools colorFromHEXString:@"c2c8da"];
        bgView.bg1mmColor = [vhECGTools colorFromHEXString:@"ebecf0"];
        bgView.bg10mmWidth = 1.f;
        bgView.bg5mmWidth = 0.5f;
        bgView.bg1mmWidth = 0.3f;
        bgView.pixPermm = 6.2f;
        [self addSubview:bgView];
        
        control3x4 = [[UIECGReview3x4Controler alloc] initWithFrame:CGRectMake(0.f, 0.f, frame.size.width, frame.size.height)];
        control3x4.userInteractionEnabled = NO;
        control3x4.handler = ^(ECGLead targetLead) {
            strongSelf->leadImageView.image = nil;
            strongSelf->longLead = targetLead;
            if (strongSelf->longLeadChangedHandler){
                strongSelf->longLeadChangedHandler(targetLead);
            }
            [strongSelf setNeedsDisplay];
        };
        [self addSubview:control3x4];
        
        control6x2 = [[UIECGReview6x2Controler alloc] initWithFrame:CGRectMake(0.f, 0.f, frame.size.width, frame.size.height)];
        control6x2.userInteractionEnabled = NO;
        control6x2.handler = ^(ECGLead targetLead) {
            strongSelf->leadImageView.image = nil;
            strongSelf->longLead = targetLead;
            if (strongSelf->longLeadChangedHandler){
                strongSelf->longLeadChangedHandler(targetLead);
            }
            [strongSelf setNeedsDisplay];
        };
        [self addSubview:control6x2];

        locationView = [[UIECGReviewLocationView alloc] initWithFrame:CGRectMake(0.f, 0.f, 10.f, 10.f)];
        locationView.alpha = 0.f;
        locationView.minX = 7.5f * bgView.pixPermm;
        locationView.handler = ^(float precent) {
//            NSLog(@"Move to:%.2f", precent);
            self->shortLeadPrecent = precent;
            [strongSelf setNeedsDisplay];
        };
        [self addSubview:locationView];
        
        style = NSECGRealTimeView_Style_3x4;
    }
    return self;
}

-(void)refreshLocationView{
    if (NO == isContinunceMode && (style == NSECGRealTimeView_Style_6x2 || style == NSECGRealTimeView_Style_3x4)){
        //这里画一个阴影，用于表现当前同步模式下，显示的短导联位置
        float lineSpace = self.frame.size.height/4.33f;
        float shortLeadWidth = (self.frame.size.width - 7.5f * pix_per_mm)/4.f;
        float yMiddle = 3.66f * lineSpace;
        if (style == NSECGRealTimeView_Style_6x2){
            lineSpace = self.frame.size.height/7.33f;
            shortLeadWidth = (self.frame.size.width - 7.5f * pix_per_mm)/2.f;
            yMiddle = 6.66f * lineSpace;
        }
        float dropAvailableWidth = self.frame.size.width - 7.5f * pix_per_mm - shortLeadWidth;
        float x = 7.5f * pix_per_mm + shortLeadPrecent * dropAvailableWidth;
        [locationView setFrame:CGRectMake(x,  yMiddle - 10.f * pix_per_mm, shortLeadWidth, 20.f * pix_per_mm)];
        locationView.alpha = 1.f;
    }else{
        locationView.alpha = 0.f;
    }
}

-(void)setIsContinunceMode:(BOOL)_isContinunceMode{
    isContinunceMode = _isContinunceMode;
    [self refreshLocationView];
}

-(void)setEcgsArray:(NSArray<NSArray<NSNumber *> *> *)_ecgsArray{
    ecgsArray = _ecgsArray;
    shortLeadPrecent = 0.5f;
    [self refreshLocationView];
    [self setNeedsDisplay];
}

-(void)setX_speed:(float)_x_speed{
    x_speed = _x_speed;
    [self setNeedsDisplay];
}

-(void)setY_rate:(float)_y_rate{
    y_rate = _y_rate;
    [self setNeedsDisplay];
}

-(void)setPix_per_mm:(float)_pix_per_mm{
    pix_per_mm = _pix_per_mm;
    locationView.minX = 7.5f * pix_per_mm;
    bgView.pixPermm = pix_per_mm;
    control3x4.pixPermm = pix_per_mm;
    control6x2.pixPermm = pix_per_mm;
    [self setNeedsDisplay];
}

-(void)setECG_rate:(float)_ECG_rate{
    ECG_rate = _ECG_rate;
    [self setNeedsDisplay];
}

-(void)setStyle:(NSECGRealTimeView_Style)_style{
    style = _style;
    leadImageView.image = nil;
    control6x2.userInteractionEnabled = NO;
    control3x4.userInteractionEnabled = NO;
    switch (style) {
        case NSECGRealTimeView_Style_6x2:
            control6x2.userInteractionEnabled = YES;
            break;
        case NSECGRealTimeView_Style_3x4:
            control3x4.userInteractionEnabled = YES;
            break;
        default:
            break;
    }
    shortLeadPrecent = 0.5f;
    [self refreshLocationView];
    [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];

    if (0.f == x_speed || 0.f == y_rate || 0.f == pix_per_mm || 0.f == ECG_rate){
        return;
    }
    if (nil == ecgsArray || 0 == ecgsArray.count){
        return;
    }
    
    if (nil == leadImageView.image){
        UIGraphicsBeginImageContextWithOptions(self.frame.size, 0, UIScreen.mainScreen.scale);
    }
    CGMutablePathRef path = nil;
    switch (style) {
        case NSECGRealTimeView_Style_12x1:
            path = [vhECGPath build12x1Path:ecgsArray zeroX:2.5f * pix_per_mm pointPerPoint:pix_per_mm * x_speed / ECG_rate zeroY:0.f rateY:y_rate lineSpace:self.frame.size.height/12.33f pix:pix_per_mm];
            if (nil == leadImageView.image){
                [vhECGPath draw12x1LeadName:leadNameFontDictionary startX:2.5f * pix_per_mm startY:0.f lineSpace:self.frame.size.height/12.33f pixPermm:pix_per_mm];
            }
            break;
        case NSECGRealTimeView_Style_3x4:{
            float widthPerPoint = pix_per_mm * x_speed / ECG_rate;
            float lineSpace = self.frame.size.height/4.33f;
            if (isContinunceMode){
                path = [vhECGPath build3x4ContinuncePath:ecgsArray fullLead:longLead zeroX:2.5f * pix_per_mm pointPerPoint:widthPerPoint zeroY:0.f rateY:y_rate lineSpace:lineSpace pix:pix_per_mm];
            }else{
                int fromIndex = (ecgsArray.firstObject.count * 0.75f) * shortLeadPrecent;
                path = [vhECGPath build3x4Path:ecgsArray fullLead:longLead ecgFromIndex:fromIndex zeroX:2.5f * pix_per_mm pointPerPoint:widthPerPoint zeroY:0.f rateY:y_rate lineSpace:lineSpace pix:pix_per_mm];
            }
            if (nil == leadImageView.image){
                float ecgWidth = widthPerPoint * ecgsArray.firstObject.count/4.f;
                float rowWidth = (self.frame.size.width - 2.5f * pix_per_mm - 5.f * pix_per_mm)/4.f;
                if (ecgWidth < rowWidth){
                    //ECG 不满屏情况下，均匀分布列，而不是靠前
                    ecgWidth = rowWidth;
                }
                [vhECGPath draw3x4LeadName:leadNameFontDictionary fullLead:longLead zeroX:2.5f * pix_per_mm ecgWidth:ecgWidth zeroY:0.f lineSpace:lineSpace pix:pix_per_mm];
            }
            break;}
        case NSECGRealTimeView_Style_6x2:{
            float widthPerPoint = pix_per_mm * x_speed / ECG_rate;
            float lineSpace = self.frame.size.height/7.33f;
            if (isContinunceMode){
                path = [vhECGPath build6x2ContinuncePath:ecgsArray fullLead:longLead zeroX:2.5f * pix_per_mm pointPerPoint:widthPerPoint zeroY:0.f rateY:y_rate lineSpace:lineSpace pix:pix_per_mm];
            }else{
                int fromIndex = (ecgsArray.firstObject.count /2.f) * shortLeadPrecent;
                path = [vhECGPath build6x2Path:ecgsArray fullLead:longLead ecgFromIndex:fromIndex zeroX:2.5f * pix_per_mm pointPerPoint:widthPerPoint zeroY:0.f rateY:y_rate lineSpace:lineSpace pix:pix_per_mm];
            }
            if (nil == leadImageView.image){
                float ecgWidth = widthPerPoint * ecgsArray.firstObject.count/2.f;
                float rowWidth = (self.frame.size.width - 2.5f * pix_per_mm - 5.f * pix_per_mm)/2.f;
                if (ecgWidth < rowWidth){
                    //ECG 不满屏情况下，均匀分布列，而不是靠前
                    ecgWidth = rowWidth;
                }
                [vhECGPath draw6x2LeadName:leadNameFontDictionary fullLead:longLead zeroX:2.5f * pix_per_mm ecgWidth:ecgWidth zeroY:0.f lineSpace:lineSpace pix:pix_per_mm];
            }
            break;}
        case NSECGRealTimeView_Style_limb_leads:
            path = [vhECGPath buildLIMBPath:ecgsArray zeroX:0.f pointPerPoint:pix_per_mm * x_speed / ECG_rate zeroY:0.f rateY:y_rate lineSpace:self.frame.size.height/7.f pix:pix_per_mm];
            if (nil == leadImageView.image){
                [vhECGPath drawLIMBLeadName:leadNameFontDictionary startX:0.f startY:0.f lineSpace:self.frame.size.height/7.f pixPermm:pix_per_mm];
            }
            break;
        case NSECGCustom_Style:{
            if (nil == dataSource){
                NSLog(@"Custom Style must have datasource, and return Leads of customized.");
                return;
            }
            NSArray *array = [dataSource customizedLeads];
            NSInteger num = array.count;
            path = [vhECGPath buildCustomPath:ecgsArray zeroX:0.f pointPerPoint:pix_per_mm * x_speed / ECG_rate zeroY:0.f rateY:y_rate lineSpace:self.frame.size.height/(num + 1) pix:pix_per_mm customLeads:array];
            if (nil == leadImageView.image){
                [vhECGPath drawCustomLeadName:leadNameFontDictionary startX:0.f startY:0.f lineSpace:self.frame.size.height/(num + 1) pixPermm:pix_per_mm customLeads:array];
            }
            break;}
        default:
            break;
    }

    if (nil == leadImageView.image){
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        if (nil == leadImageView){
            leadImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.f, 0.f, self.frame.size.width, self.frame.size.height)];
            leadImageView.backgroundColor = [UIColor clearColor];
            [self insertSubview:leadImageView aboveSubview:bgView];
        }
        leadImageView.image = image;
    }
    
    if (ecgShapeLayer){
        [ecgShapeLayer removeFromSuperlayer];
    }
    ecgShapeLayer = [CAShapeLayer layer];
    ecgShapeLayer.path = path;
    ecgShapeLayer.lineWidth = lineWidth;
    ecgShapeLayer.strokeColor = lineColor.CGColor;
    ecgShapeLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer insertSublayer:ecgShapeLayer above:bgView.layer];
    
    [self bringSubviewToFront:locationView];
    CGPathRelease(path);
    
}

@end
